﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Collections.Specialized;

namespace Facebook_Graph_Toolkit.Helpers {
    /// <summary>
    /// Produces an Api object from data given by Facebook
    /// </summary>
    public class ApiProducer {
        /// <summary>
        /// Produce an Api object from the given [code] data and the given Facebook App config data
        /// </summary>
        /// <param name="context">The HttpContext which contains the [code] parameter response from Facebook</param>
        /// <param name="config">Facebook App config</param>
        /// <returns>Api object</returns>
        public static GraphApi.Api GetApiFromCode(HttpContext context, FacebookAppConfig config = null) {
            if (string.IsNullOrEmpty(context.Request.QueryString["code"])) throw new ArgumentOutOfRangeException("Unable to produce Facebook Api: [code] parameter is missing in querystring");

            if (config == null) config = new FacebookAppConfig();
            config.GetDefaultConfig();

            string path = context.Request.Url.AbsoluteUri;
            if (path.IndexOf('?') != -1) path = path.Substring(0, path.IndexOf('?'));
            NameValueCollection NVC = new NameValueCollection(context.Request.QueryString);
            NVC.Remove("code");
            if (NVC.Count > 0) {
                path += '?';
                for (int i = 0; i < NVC.Count; i++) {
                    path += NVC.Keys[i] + '=' + NVC.Get(i);
                    if (i != NVC.Count - 1) path += '&';
                }
            }

            string OAuthUrl = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}", config.FacebookAppID, path, config.FacebookAppSecret, context.Request.QueryString["code"]);
            string OAuthResponse = Helpers.WebResponseHelper.GetWebResponse(OAuthUrl);
            string[] OAuthResponseArray = OAuthResponse.Split('&');
            IDictionary<string, string> OAuthParameters = new Dictionary<string, string>();
            foreach (string s in OAuthResponseArray) {
                string[] KVP = s.Split('=');
                OAuthParameters.Add(KVP[0], KVP[1]);
            }
            if (OAuthParameters.ContainsKey("expires")) return new GraphApi.Api(OAuthParameters["access_token"], DateTime.UtcNow.AddSeconds(Convert.ToInt32(OAuthParameters["expires"])));
            else return new GraphApi.Api(OAuthParameters["access_token"]);
        }
    }
}
